<template>
  <div>
    <el-tabs
      v-model="pageCurrent"
      type="card"
      closable
      @tab-click="tabChange"
      @tab-remove="removeTab"
    >
      <el-tab-pane v-for="item in pageList" :key="item.name" :name="item.name">
        <span slot="label">
          <span>{{ item.label }}</span>
          <span class="refresh">
            <i
              style="font-size: 15px"
              @click="refreshModule"
              class="el-icon-refresh"
            >111</i>
          </span>
        </span>
      </el-tab-pane>
    </el-tabs>

    <keep-alive :exclude="exclude">
      <router-view v-if="condition" ref="view" />
    </keep-alive>
  </div>
</template>

<script>
export default {
  data() {
    return {
      pageCurrent: "",
      pageList: [],
      exclude: null,
      condition: true,
    };
  },

  watch: {
    $route: {
      handler(to, form = null) {
        //当路由改变时，检测该路由是否已经在打开的页面之中，如果不在，就添加进去
        this.pageCurrent = to.path;
      },
      immediate: true,
    },
  },

  methods: {
    removeTab(targetName) {
      let tabs = this.pageList;
      let activeName = this.pageCurrent;
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.name;
            }
          }
        });
      }
      this.pageCurrent = activeName;
      this.pageList = tabs.filter((tab) => tab.name !== targetName);
      this.$router.push({ path: activeName });
    },
    tabChange(tab, event) {
      this.$router.push({ path: tab.name });
    },
    refreshModule() {
      this.exclude = this.$refs.view.$options.name;
      this.condition = !this.condition;
      this.$nextTick((_) => {
        this.exclude = null;
        this.condition = !this.condition;
      });
    },
  },
};
</script>

<style lang="less" scoped>
</style>